// Copyright 2009 StarCite Inc.  All rights reserved.
// Consumer.java 3:11:41 PM danny.liu
package com.billowsoft.sample.thread.lock;

/**
 * @author danny.liu Apr 18, 2012
 * @version 1.0
 * 
 */
public class Consumer extends Thread {

	private ProductFactory factory;
	private String consumerName;

	public Consumer(ProductFactory factory, String consumerName) {
		this.factory = factory;
		this.consumerName = consumerName;
	}

	@Override
	public void run() {

		while (true) {
			factory.lock();
			try {
				if (factory.hasProduct()) {
					Product product = factory.getProduct();
					saySomething("I'm lucky, got one product from factory: "
							+ product.getProductNumber());
				} else {
					saySomething("Factory has no product now, I will wait.");
				}
			} finally {
				factory.unlock();
			}
			
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
	}

	private void saySomething(String message) {
		System.out.println(consumerName + ": " + message);
	}
}
